package com.lyf.shop.web.controller;

import com.lyf.shop.common.Const;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        if(method == null){
            method="index";
        }
        try {
            Class userConClass = this.getClass();
            Method method1 = userConClass.getMethod(method,HttpServletRequest.class,HttpServletResponse.class);
            Object invoke = method1.invoke(this,request,response);
            if(invoke!=null){
                String path = (String) invoke;
                if (path.contains(Const.FORWARD)){
                    request.getRequestDispatcher(path.substring(path.indexOf(Const.COLON)+1)).forward(request,response);
                }else if(path.contains(Const.REDIRECT)){
                    response.sendRedirect(request.getContextPath()+path.substring(path.indexOf(Const.COLON)+1));
                }else {
                    response.getWriter().println(path);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","非常抱歉，页面暂时无法访问，请稍后再试");
            request.getRequestDispatcher("/message.jsp").forward(request,response);
        }
    }

    //如果method为空，就会执行这个方法，返回到首页页面index.jsp
    protected void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect(request.getContextPath()+"/index.jsp");
    }
}
